
package com.zany.util.BeansUtil;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

public class RequestBeanUtil {
	 /**
	   * 传递一个BEAN类型,自动从REQUEST里获得参数送BEAN对象返回
	   * @param beanclazz  BEAN类型
	   * @param request  request
	   * @return
	   * @throws Exception  错误返回
	   */	
	  public static Object getReqToBean(Class beanclazz,HttpServletRequest request) throws Exception{
	  		Object obj = Class.forName(beanclazz.getName()).newInstance();
	  		PropertyDescriptor[] props1 = BeanInfoUtil.getPropertyDescriptors(beanclazz);
	  		for(int n=0;n<props1.length;n++){
	  			String name = BeanInfoUtil.getName(props1[n]);
	  			String flag = request.getParameter(name.trim());
	  			if(flag!=null&&!"".equals(flag.trim())){
	  				Method setMethod = BeanInfoUtil.getWriteMethod(props1[n]);
	  				Object typeVal=new Object();
	  				String type=BeanInfoUtil.getTypeName(props1[n]);
					if (type.equals("java.lang.Double")||type.equals("double")) {
						typeVal = new Double(new String(flag).trim());
					} else if (type.equals("java.lang.String")||type.equals("string")) {
						typeVal = new String(flag).trim();
					} else if (type.equals("java.math.BigDecimal")) {
						typeVal = new BigDecimal(new String(flag).trim());
					} else if (type.equals("java.lang.Long")||type.equals("long")) {
						typeVal = new Long(new String(flag).trim());
					} else if (type.equals("java.util.Date")) {
						//typeVal = new Long(new String(flag).trim());
						Date mydate  =new Date();
						mydate.setYear(Integer.valueOf(flag.trim().substring(0,4)).intValue()-1900);
						mydate.setMonth(Integer.valueOf(flag.trim().substring(4,6)).intValue()-1);
						mydate.setDate(Integer.valueOf(flag.trim().substring(6)).intValue());
						typeVal=mydate;
					} else if (type.equals("java.lang.Float")||type.equals("float")) {
						typeVal = new Float(new String(flag).trim());
					} else if (type.equals("java.lang.Integer")||type.equals("int")) {
						typeVal = new Integer(new String(flag).trim());
					}
	  				setMethod.invoke(obj,new Object[]{typeVal});
	  			}
	  		}
	  		return obj;
	  }
}
